const fs = require('fs');
const path = require('path');
const download = require('download');
const { BaseDownloader } = require('./BaseDownloader');
const { DownloadStatus } = require('../../common/DownloadStatus');

class MP4Downloader extends BaseDownloader {
    constructor(options) {
        super(options);
        this.timeout = options.timeout || 30000;
    }

    async start() {
        try {
            this.status = DownloadStatus.Downloading;
            this.ensureDownloadDir();
            
            const outputPath = path.join(this.dir, `${this.taskName}.mp4`);
            await this.downloadFile(outputPath);
            
            this.emitComplete();
        } catch (err) {
            this.emitError(err);
        }
    }

    async downloadFile(outputPath) {
        return new Promise((resolve, reject) => {
            const stream = download(this.url, outputPath, {
                filename: `${this.taskName}.mp4`,
                headers: this.headers,
                timeout: this.timeout
            });
            
            stream.on('response', res => {
                const totalSize = parseInt(res.headers['content-length'], 10);
                let downloadedSize = 0;
                
                res.on('data', chunk => {
                    if (this.shouldStop()) {
                        stream.destroy();
                        this.stop();
                        resolve();
                        return;
                    }
                    downloadedSize += chunk.length;
                    const progress = Math.round((downloadedSize / totalSize) * 100);
                    this.emit('download-progress', {
                        downloaded: downloadedSize,
                        total: totalSize,
                        progress
                    });
                    this.emitProgress(progress);
                });
            });
            
            stream.on('finish', () => {
                if (!this.shouldStop()) {
                    resolve();
                }
            });
            stream.on('error', err => {
                if (err.message !== 'Download stopped by user') {
                    this.emit('download-error', err);
                    reject(err);
                }
            });
        });
    }
}

module.exports = MP4Downloader;
